package com.dspot.declex.helper;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.lang.model.element.Element;

import com.dspot.declex.parser.LayoutsParser;
import com.dspot.declex.parser.LayoutsParser.LayoutObject;

import org.ohosannotations.OhosAnnotationsEnvironment;
import org.ohosannotations.annotations.EAbility;
import org.ohosannotations.annotations.EFraction;
import org.ohosannotations.rclass.IRClass;

public class ViewsHelper {

	private LayoutsParser layoutParser;

	private Element element;
	private OhosAnnotationsEnvironment environment;

	private String layoutId;
	private Map<String, LayoutObject> layoutObjects;

	public ViewsHelper(Element element, OhosAnnotationsEnvironment environment) {

		this.layoutParser = LayoutsParser.getInstance();
		this.element = element;
		this.environment = environment;

		getLayoutInformation();
	}

	private void getLayoutInformation() {

		EAbility ability = element.getAnnotation(EAbility.class);
		if (ability != null) {
			int layout = ability.value();
			if (layout != -1) {
//				String idQualifiedName = environment.getRClass()
//						.get(IRClass.Res.LAYOUT).getIdQualifiedName(layout);
				String idQualifiedName = environment.getRClass().getIdQualifiedNameById(layout);
				Matcher matcher = Pattern.compile("\\.(\\w+)$").matcher(
						idQualifiedName);

				if (matcher.find()) {
					layoutId = rename(matcher.group(1));
					layoutObjects = layoutParser.getLayoutObjects(layoutId);
				}
			}
		}

		EFraction fragment = element.getAnnotation(EFraction.class);
		if (fragment != null) {
			int layout = fragment.value();
			if (layout != -1) {
//				String idQualifiedName = environment.getRClass()
//						.get(IRClass.Res.LAYOUT).getIdQualifiedName(layout);
				String idQualifiedName = environment.getRClass().getIdQualifiedNameById(layout);
				Matcher matcher = Pattern.compile("\\.(\\w+)$").matcher(
						idQualifiedName);

				if (matcher.find()) {
					layoutId = rename(matcher.group(1));
					layoutObjects = layoutParser.getLayoutObjects(layoutId);
				}
			}
		}
	}

	private String rename(String layoutName) {
		String layout = "Layout_";
		if (layoutName.startsWith(layout)) {
			layoutName = layoutName.substring(layout.length());
		}
		return layoutName;
	}

	public String getLayoutId() {
		return layoutId;
	}

	public Map<String, LayoutObject> getLayoutObjects() {
		return layoutObjects;
	}

	public Map<String, LayoutObject> getLayoutObjects(String layoutId) {
		if (layoutId.equals(this.layoutId)) return layoutObjects;

		return layoutParser.getLayoutObjects(layoutId);
	}

}
